import '@/assets/svgs'
import { blackList } from '@/config'
import 'amfe-flexible' // 移动端适配
import Vue from 'vue'
import App from './App.vue'
import './plugins/vant.js' // 按需全局引入vant组件
import router from './router'
import store from './store'

Vue.config.productionTip = false

// 监听浏览器onpopstate事件,设置操作类型
window.addEventListener(
  'popstate',
  () => {
    store.commit('SET_ISBACK', true)
  },
  false
)

// 在路由守卫中动态处理页面是否进行缓存
router.beforeEach((to, from, next) => {
  const isBack = store.getters.isBack
  const buffer = store.getters.keepAlivePages
  if (isBack) {
    // 从数组中移除(考虑到存在跨层级返回的情况，将目标路由以后的数据都删除)
    const index = buffer.indexOf(to.name)
    if (index !== -1) {
      buffer.splice(index + 1, buffer.length - index - 1)
    }
  } else {
    // 加入数组,push操作都要加入缓存数组
    const index = buffer.indexOf(from.name)
    if (index === -1 && from.name && !blackList.includes(from.name)) {
      buffer.push(from.name)
    }
    const indexTo = buffer.indexOf(to.name)
    if (indexTo === -1 && to.name && !blackList.includes(to.name)) {
      buffer.push(to.name)
    }
  }
  store.commit('SET_KEEPALIVEPAGES', buffer)
  next()
})

// 全局混入处理页面滚动条
Vue.mixin({
  activated() {
    const contentDom = document.querySelector('.layout-content')
    contentDom.scrollTop = this.$route.meta.scrollTop
  }
})

// 导出vue实例，用事件总线的模式处理组件之间的通信
const app = new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

export default app
